package com.seventh.parkingrent.controller;


import com.seventh.parkingrent.commens.Result;
import com.seventh.parkingrent.controller.form.PropertyManagerForm;
import com.seventh.parkingrent.service.IPropertyManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2021-08-25
 */
@RestController
@Slf4j
@CrossOrigin("*")
public class PropertyManagerController {
    @Resource
    private IPropertyManagerService propertyManagerService;

    @PostMapping("/registerPropertyManager")
    public Result registerPropertyManager(@Valid @RequestBody PropertyManagerForm form, BindingResult bindingResult) throws NoSuchAlgorithmException {
        log.info("获得物业注册信息form={}",form);
        if (bindingResult.hasErrors()) {
            return getBindingResult(bindingResult);
        }

        Result result = propertyManagerService.register(form);
        return result;
    }

    @GetMapping("/getPropertyManagerName")
    public Result getPropertyManagerName(){
        log.info("前端提请所有物业的名字");
        List<String> propertyManagerNames = propertyManagerService.selectPropertyManagerName();

        return Result.success(propertyManagerNames);
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        log.info("前端传来了一个文件");
        file.transferTo(new File("D:/thirdstep/parking-rent-nodejs-for-manager-client/src/assets" + file.getOriginalFilename()));
        return Result.success(file.getOriginalFilename());
    }

    public Result getBindingResult(BindingResult bindingResult){
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            stringBuilder.append(fieldError.getField()+"："+fieldError.getDefaultMessage()+";");
        }
        return Result.fail("10086",stringBuilder.toString());
    }
}

